
#include "Loop.h"
#include "NavigatorNode.h"

using namespace ttg;
using namespace ttg_internal::pipeline;

//------------
//--- Loop ---
//------------

bool Loop::findPath(std::vector<NavigatorNode *> &path, NavigatorNode *first, NavigatorNode *last)
{
	path.push_back(first);
	for (size_t i = 0; i < first->getOutputs().size(); i++)
	{
		if (findPath(path, first->getOutputs()[i], last))
			return true;
	}
	path.pop_back();
	return false;
}

Loop::Loop(NavigatorNode *first, NavigatorNode *last)
{
	if (!findPath(nodes, first, last))
		throw Error(Error::FATAL, "Loop", "Loop",
					"Ports to parallel or next nodes are not supported yet");
	node_states.resize(nodes.size());
	this->node_with_tasks = 0;
}

bool Loop::shouldFinishIteration(size_t node_id, int active_inputs)
{
	/*//Setting info.
	if (can_produce_tasks ^ (node_states[node_id].get() == 1))
	{
		if (can_produce_tasks)
		{
			active_nodes++;
			node_states[node_id] = 1;
		}
		else
		{
			active_nodes--;
			node_states[node_id] = 0;
		}
	}
	//
	if (node_id == node_with_tasks && !can_produce_tasks && active_inputs == 0)
		;*/
	return false;
}

void Loop::notify(size_t node_id, bool has_tasks)
{
}

void Loop::startIteration(size_t node_id)
{
	if (node_id == 0)
	{
		this->node_with_tasks = 0;
		active_nodes = 0;
		for (size_t i = 0; i < node_states.size(); i++)
			node_states[i] = 0;
	}
}

size_t Loop::getID(NavigatorNode *node)
{
	for (size_t i = 0; i < nodes.size(); i++)
		if (nodes[i] == node)
			return i;
	throw Error(Error::FATAL, "Loop", "getID",
				"Node does not belong to loop");
}
